export const base64ConvertFile = (urlData: string, filename: string): File => {// 64转file
    var arr = urlData.split(',');
    // @ts-ignore
    var type = arr[0].match(/:(.*?);/)[1];
    var fileExt = type.split('/')[1];
    var bstr = atob(arr[1]);
    var n = bstr.length;
    var u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, {
        type: type
    });
}

export const getNewFile = async (file: File): Promise<File> => {
    const base64String = await convertFileToBase64(file);
    const newFile = base64ConvertFile(base64String, file.name);
    return new Promise((resolve, reject) => {
        resolve(newFile)
    })
}

export const convertFileToBase64 = (file: File): Promise<string> => {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();

        reader.onload = (e: ProgressEvent<FileReader>) => {
            // 检查e.target.result是否存在，并且是字符串类型
            if (e.target?.result && typeof e.target.result === 'string') {
                resolve(e.target.result);
            } else {
                reject(new Error('File could not be read as base64 string'));
            }
        };

        reader.onerror = (e) => {
            reject(new Error('Error reading file'));
        };

        reader.readAsDataURL(file);
    });
}


export const isFileChanged = (file: File): Promise<boolean> => {
    return new Promise((resolve, reject) => {
        file.slice(0, 1).arrayBuffer()
            .then(() => resolve(false))
            .catch(() => reject(true))
    })
}

export async function deepCopyFile(originalFile: File) {
    return new Promise((resolve, reject) => {
        // 使用FileReader读取原始文件的内容
        const reader = new FileReader();
        reader.onload = function (e) {
            try {
                // 创建一个新的Blob对象，使用读取的结果作为内容
                // @ts-ignore
                const newBlob = new Blob([e.target.result], {type: originalFile.type});
                // 创建一个新的File对象，复制原始文件的名称和修改时间
                const newFile = new File([newBlob], originalFile.name, {
                    type: originalFile.type,
                    lastModified: originalFile.lastModified,
                });
                resolve(newFile);
            } catch (error) {
                console.log("解析file失败")
                reject(new File(["Hello"], "hello.txt", {type: "text/plain"}));
            }
        };
        reader.onerror = function (error) {
            reject(error);
        };
        reader.readAsArrayBuffer(originalFile);
    });
}


export const fileToBlob = (file: File): Promise<Blob> => {

    // 创建 FileReader 对象
    let reader = new FileReader();

    return new Promise(resolve => {
        // FileReader 添加 load 事件
        reader.addEventListener('load', (e) => {
            let blob;
            // @ts-ignore
            if (typeof e.target.result === 'object') {
                // @ts-ignore
                blob = new Blob([e.target.result])
            } else {
                // @ts-ignore
                blob = e.target.result
            }
            console.log(Object.prototype.toString.call(blob));
            // @ts-ignore
            resolve(blob)
        })
        // FileReader 以 ArrayBuffer 格式 读取 File 对象中数据
        reader.readAsArrayBuffer(file)
    })
}